package com.ruoyi.cms.controller.admin;

import cn.hutool.core.util.IdUtil;
import com.ruoyi.cms.common.BaseController;
import com.ruoyi.cms.domain.Variable;
import com.ruoyi.cms.exception.AdminGeneralException;
import com.ruoyi.cms.exception.CmsException;
import com.ruoyi.cms.service.VariableService;
import com.ruoyi.cms.util.ExceptionEnum;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.helper.LoginHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/cms/variable")
public class VariableController extends BaseController {
    @Autowired
    private VariableService variableService;

    @GetMapping("/list")
    public R<List<Variable>> list() {
        return R.ok(variableService.selectVariableList());
    }

    @GetMapping("/find/{id}")
    public R<Variable> get(@PathVariable(name = "id") String id) {
        return R.ok(variableService.queryVariableId(id));
    }

    @PostMapping("/save")
    public R<String> save(@RequestBody Variable variable) throws CmsException {
        Variable temp = variableService.queryVariableByName(variable.getItemName());
        if(temp != null) {
            throw new AdminGeneralException(
                ExceptionEnum.VARIABLE_EXIST_EXCEPTION.getCode(),
                ExceptionEnum.VARIABLE_EXIST_EXCEPTION.getMessage(),
                "变量名已经存在，请检查变量名。");
        }

        variable.setId(IdUtil.getSnowflake().nextIdStr());
        variable.setCreateBy(LoginHelper.getLoginUser().getLoginId());
        variable.setCreateTime(new Date());
        try {
            variableService.add(variable);
        } catch (Exception e) {
            throw new AdminGeneralException(
                ExceptionEnum.HTTP_INTERNAL_SERVER_ERROR.getCode(),
                ExceptionEnum.HTTP_INTERNAL_SERVER_ERROR.getMessage(),
                e.getMessage());
        }
        return R.ok();
    }

    @PostMapping("/update")
    public R<String> update(@RequestBody Variable variable) throws CmsException {
        variableService.updateVariable(variable);
        return R.ok();
    }

    @PostMapping("delete/{id}")
    public int deleteForm(@PathVariable(value = "id", required = false)String id) {
        return variableService.deleteVariable(id);
    }
}
